﻿using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;


namespace Util.XamariN.AttachUtils
{
    public static class Focus
    {
        #region IsFocus

        public static readonly BindableProperty IsFocusProperty = BindableProperty.CreateAttached
        (
            propertyName: "IsFocus",
            returnType: typeof(bool),
            declaringType: typeof(VisualElement),
            defaultValue: false,
            defaultBindingMode: BindingMode.OneWayToSource
        );

        public static bool GetIsFocus(BindableObject view)
        {
            return (bool)view.GetValue(IsFocusProperty);
        }

        public static void SetIsFocus(BindableObject view, bool value)
        {
            view.SetValue(IsFocusProperty, value);
        }

        #endregion

        #region IsEnabled - 启用 IsFocus 附加属性

        public static readonly BindableProperty IsEnabledProperty = BindableProperty.CreateAttached
        (
            propertyName: "IsEnabled",
            returnType: typeof(bool),
            declaringType: typeof(VisualElement),
            defaultValue: false,
            propertyChanged: onHandle_IsEnabled_PropertyChanged
        );

        public static void SetIsEnabled(BindableObject dp, bool value)
        {
            dp.SetValue(IsEnabledProperty, value);
        }

        public static bool GetIsEnabled(BindableObject dp)
        {
            return (bool)dp.GetValue(IsEnabledProperty);
        }

        private static void onHandle_IsEnabled_PropertyChanged(BindableObject sender, object objOldValue, object objNewValue)
        {
            if (sender is VisualElement visualElement)
            {
                if (objOldValue is bool oldValue && oldValue == true)
                {
                    visualElement.Focused -= onHandleFocused;
                    visualElement.Unfocused -= onHandleUnfocused;
                }
                if (objNewValue is bool newValue && newValue == true)
                {
                    visualElement.Focused += onHandleFocused;
                    visualElement.Unfocused += onHandleUnfocused;
                }
            }
        }

        private static void onHandleFocused(object sender, FocusEventArgs e)
        {
            if (sender is VisualElement element)
            {
                SetIsFocus(element, e.IsFocused);
            }
        }

        private static void onHandleUnfocused(object sender, FocusEventArgs e)
        {
            if (sender is VisualElement element)
            {
                SetIsFocus(element, e.IsFocused);
            }
        }

        #endregion
    }
}
